//
//  YSSecuritiesList.m
//  GuBoShi
//
//  Created by BaHCy on 2017/3/29.
//  Copyright © 2017年 YiShi. All rights reserved.
//

#import "YSSecuritiesList.h"
#import "YSSecurities.h"
#import "YSSecuritiesDB.h"

@interface YSSecuritiesList()

@property (nonatomic, strong) dispatch_queue_t concurrentQueue;
@end

@implementation YSSecuritiesList

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.concurrentQueue = dispatch_queue_create("com.ys.lg.YSQuoteList",
                                                       DISPATCH_QUEUE_CONCURRENT);
        
        quoteMirror = [NSMutableDictionary new];
    }
    return self;
}

- (YSSecurities *) getQuoteWithEI:(NSString *) EI {
    YSSecurities *item = [quoteMirror objectForKey:EI];
    if (item) {
        return item;
    }else{
        item = [[YSSecuritiesDB sharedManager] getDataWithEiFromDB:EI];
        dispatch_barrier_async(self.concurrentQueue, ^{
            [self addQuote:item];
        });
    }
    return item;
}

- (BOOL) addQuote:(YSSecurities *) quote {
    
    if (![self validQuote:quote]) return NO;
    
    dispatch_barrier_async(self.concurrentQueue, ^{
        [quoteMirror setObject:quote forKey:quote.IdStr];
    });
    return YES;
}

- (BOOL) mergeQuote:(YSSecurities *) quote {
    
    dispatch_barrier_async(self.concurrentQueue, ^{
        YSSecurities *storeQuote = [quoteMirror valueForKey:quote.IdStr];
        [storeQuote updateWithQuote:quote];
        NSLog(@"%@",storeQuote);
        [quoteMirror setValue:storeQuote forKey: storeQuote.IdStr];
    });
    return YES;
}

- (BOOL)validQuote:(YSSecurities *) ss{
    
    if (!ss) return NO;
    if (!ss.isValidID) return NO;
    
    return YES;
}

@end
